import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_wan_android/generated/l10n.dart';
import 'package:flutter_wan_android/manager/router_manger.dart';
import 'package:flutter_wan_android/provider/provider_widget_consumer.dart';
import 'package:flutter_wan_android/utils/resource_mananger.dart';
import 'package:flutter_wan_android/view_model/login_model.dart';
import 'package:flutter_wan_android/view_model/theme_model.dart';
import 'package:flutter_wan_android/view_model/user_model.dart';
import 'package:flutter_wan_android/widget/activity_indicator.dart';
import 'package:flutter_wan_android/widget/bottom_clipper.dart';
import 'package:provider/provider.dart';

class UserPage extends StatefulWidget {
  @override
  _UserPageState createState() => _UserPageState();
}

class _UserPageState extends State<UserPage> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        body: CustomScrollView(
      slivers: <Widget>[
        SliverAppBar(
          actions: <Widget>[
            ///登出按钮
            ProviderWidgetConsumer<LoginModel>(
                model: LoginModel(Provider.of<UserModel>(context)),
                builder: (context, model, child) {
                  if (model.isBusy) {
                    return Padding(
                      padding: const EdgeInsets.only(right: 15.0),
                      child: ActivityIndicator(
                        brightness: Brightness.dark,
                      ),
                    );
                  }
                  if (model.userModel.hasUser) {
                    return IconButton(
                      tooltip: S.of(context).logout,
                      icon: Icon(Icons.exit_to_app),
                      onPressed: () {
                        model.logout();
                      },
                    );
                  }
                  return SizedBox.shrink();
                })
          ],
          backgroundColor: Theme.of(context).scaffoldBackgroundColor,
          expandedHeight: 200 + MediaQuery.of(context).padding.top,
          flexibleSpace: UserHeaderWidget(),
          pinned: false,
        ),
        UserListWidget(),
      ],
    ));
  }
}

///
/// 头部登录页
///
class UserHeaderWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ClipPath(
        clipper: BottomClipper(),
        child: Container(
            color: Theme.of(context).primaryColor.withAlpha(200),
            padding: EdgeInsets.only(top: 10),
            child: Consumer<UserModel>(
                builder: (context, model, child) => InkWell(
                    onTap: model.hasUser ? null : () => RoutesManager.getInstance().pushLoginPage(context),
                    child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          ///用户头像
                          InkWell(
                            child: ClipOval(
                              child: model.hasUser
                                  ? CachedNetworkImage(
                                      imageUrl: ImageHelper.randomUrl(key: model.user.id, width: 100, height: 100),
                                      placeholder: (context, url) => ImageHelper.placeHolder(width: 100, height: 100),
                                      errorWidget: (context, url, error) => ImageHelper.error(width: 100, height: 100))
                                  : Image.asset(ImageHelper.wrapImageAssets('user_avatar.png'),
                                      color: Colors.white,
                                      fit: BoxFit.fill,
                                      width: 90,
                                      height: 90,
                                      // https://api.flutter.dev/flutter/dart-ui/BlendMode-class.html
                                      colorBlendMode: BlendMode.colorBurn),
                            ),
                          ),
                          SizedBox(
                            height: 20,
                          ),

                          ///用户昵称
                          Column(children: <Widget>[
                            Text(model.hasUser ? model.user.nickname : S.of(context).signIn,
                                style: Theme.of(context).textTheme.headline6.apply(color: Colors.white.withAlpha(200))),
                            SizedBox(
                              height: 10,
                            ),
                          ])
                        ])))));
  }
}

class UserListWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var iconColor = Theme.of(context).accentColor;
    return ListTileTheme(
      contentPadding: const EdgeInsets.symmetric(horizontal: 30),
      child: SliverList(
        delegate: SliverChildListDelegate([
          // ListTile(
          //   title: Text(S.of(context).favourites),
          //   onTap: () {
          //     Navigator.of(context).pushNamed(RouteName.favouriteList);
          //   },
          //   leading: Icon(
          //     Icons.favorite_border,
          //     color: iconColor,
          //   ),
          //   trailing: Icon(Icons.chevron_right),
          // ),
          ListTile(
            title: Text(S.of(context).darkMode),
            onTap: () {
              switchDarkMode(context);
            },
            leading: Transform.rotate(
              angle: -pi,
              child: Icon(
                Theme.of(context).brightness == Brightness.light ? Icons.brightness_5 : Icons.brightness_2,
                color: iconColor,
              ),
            ),
            trailing: CupertinoSwitch(
                activeColor: Theme.of(context).accentColor,
                value: Theme.of(context).brightness == Brightness.dark,
                onChanged: (value) {
                  switchDarkMode(context);
                }),
          ),

          /// 主题颜色
          SettingThemeWidget(),

          ///设置
          ListTile(
            title: Text(S.of(context).setting),
            onTap: () {
              RoutesManager.getInstance().pushSettingPage(context);
            },
            leading: Icon(
              Icons.settings,
              color: iconColor,
            ),
            trailing: Icon(Icons.chevron_right),
          ),
          // ListTile(
          //   title: Text(S.of(context).appUpdateCheckUpdate),
          //   onTap: () {
          //     Navigator.push(
          //       context,
          //       CupertinoPageRoute(
          //         builder: (context) => ChangeLogPage(),
          //         fullscreenDialog: true,
          //       ),
          //     );
          //   },
          //   leading: Icon(
          //     Icons.system_update,
          //     color: iconColor,
          //   ),
          //   trailing: Icon(Icons.chevron_right),
          // ),
          SizedBox(
            height: 30,
          )
        ]),
      ),
    );
  }

  void switchDarkMode(BuildContext context) {
    if (MediaQuery.of(context).platformBrightness == Brightness.dark) {
      //showToast("检测到系统为暗黑模式,已为你自动切换", position: ToastPosition.bottom);
    } else {
      Provider.of<ThemeModel>(context, listen: false)
          .switchTheme(userDarkMode: Theme.of(context).brightness == Brightness.light);
    }
  }
}

class SettingThemeWidget extends StatelessWidget {
  SettingThemeWidget();

  @override
  Widget build(BuildContext context) {
    return ExpansionTile(
      title: Text(S.of(context).theme),
      leading: Icon(
        Icons.color_lens,
        color: Theme.of(context).accentColor,
      ),
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
          child: Wrap(
            spacing: 5,
            runSpacing: 5,
            children: <Widget>[
              ///主题颜色
              ...Colors.primaries.map((color) {
                return Material(
                  color: color,
                  child: InkWell(
                    onTap: () {
                      var model = Provider.of<ThemeModel>(context, listen: false);
                      // var brightness = Theme.of(context).brightness;
                      model.switchTheme(color: color);
                    },
                    child: Container(
                      width: 40,
                      height: 40,
                    ),
                  ),
                );
              }).toList(),

              ///随机主题
              Material(
                child: InkWell(
                  onTap: () {
                    var model = Provider.of<ThemeModel>(context, listen: false);
                    var brightness = Theme.of(context).brightness;
                    model.switchRandomTheme(brightness: brightness);
                  },
                  child: Container(
                    alignment: Alignment.topLeft,
                    decoration: BoxDecoration(border: Border.all(color: Theme.of(context).accentColor)),
                    width: 40,
                    height: 40,
                    child: Text(
                      "🌈",
                      style: TextStyle(fontSize: 40, color: Theme.of(context).accentColor),
                    ),
                  ),
                ),
              )
            ],
          ),
        ),
      ],
    );
  }
}
